﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BHXH.LinqRepository
{
    //
    public class DanhMucPhieuRepository : Repository<Phieu>
    {
       
        public IEnumerable<PhieuTemp> GetAllByLoaiPhieu(string LoaiPhieu)
        {
            var obj = (from ds in dataContext.Phieus
                       where ds.LoaiPhieu == LoaiPhieu
                       orderby ds.NgayPV descending
                       select new PhieuTemp
                       {
                           ID = ds.ID,
                           CoQuanID = ds.CoQuanID,
                           MaPhieu = ds.MaPhieu,
                           NgayPV = ds.NgayPV,
                           TenCoQuan = ds.CoQuan.Ten
                       }).ToList();
            return obj;
        }

        public Phieu GetOneById(Guid Id)
        {
            return dataContext.Phieus.Where(c => c.ID == Id).FirstOrDefault();
        }
        public void InsertOne(Phieu one)
        {
            one.ID = Guid.NewGuid();
           // Add(one);
            dataContext.Phieus.InsertOnSubmit(one);
            //dataContext.SubmitChanges();
        }
        public void EditOne(Phieu one)
        {
            //Update(one);
            //dataContext.Phieus.Attach(one, true);
            //dataContext.SubmitChanges();
        }
        public void DeleteOne(Phieu obj)
        {
            dataContext.Phieus.DeleteOnSubmit(obj);
        }

        public string getNextMaPhieu(string loaiPhieu)
        {
            string characterLoaiPhieu = loaiPhieu.Replace("Phieu", "");
            try
            {
                Phieu entity = dataContext.Phieus.Where(x => x.LoaiPhieu == loaiPhieu).OrderByDescending(x => x.MaPhieu).FirstOrDefault();

                if (entity != null)
                {
                    string s = entity.MaPhieu.Replace(characterLoaiPhieu, "").Trim();
                    int convert = int.Parse(s);
                    convert++;
                    return characterLoaiPhieu + convert.ToString("0000");
                }

            }
            catch (Exception ex)
            {
            }

            return characterLoaiPhieu + 1.ToString("0000");
        }

    }
}
